// pages/menu/menu.js
const auth = require('../../utils/auth.js');
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentCategory: "hot",
    hasUserConsent: false,
    hotDishes: [
      {
        id: "h1",
        name: "红烧狮子头",
        description: "选用上等猪肉制作，口感鲜美",
        price: 12,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish1.png",
        count: 0,
      },
      {
        id: "h2",
        name: "清蒸鲈鱼",
        description: "新鲜鲈鱼，清淡爽口",
        price: 15,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish2.png",
        count: 0,
      },
      {
        id: "h3",
        name: "宫保鸡丁",
        description: "传统川菜，口感麻辣鲜香",
        price: 10,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish3.png",
        count: 0,
      },
      {
        id: "h4",
        name: "麻婆豆腐",
        description: "正宗川味，香辣可口",
        price: 8,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish3.png",
        count: 0,
      },
      {
        id: "h5",
        name: "水煮肉片",
        description: "嫩滑多汁，香辣过瘾",
        price: 13,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/default-dish.png",
        count: 0,
      },
      {
        id: "h6",
        name: "糖醋排骨",
        description: "外酥里嫩，甜酸可口",
        price: 14,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/default-dish.png",
        count: 0,
      },
      {
        id: "h7",
        name: "北京烤鸭",
        description: "外皮酥脆，肉质鲜美",
        price: 20,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/default-dish.png",
        count: 0,
      },
      {
        id: "h8",
        name: "蒜蓉炒青菜",
        description: "清淡爽口，营养健康",
        price: 6,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish1.png	",
        count: 0,
      },
      {
        id: "h9",
        name: "酸菜鱼",
        description: "酸辣开胃，鱼肉鲜嫩",
        price: 15,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish1.png	",
        count: 0,
      },
      {
        id: "h10",
        name: "东坡肉",
        description: "肥而不腻，入口即化",
        price: 16,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish2.png",
        count: 0,
      },
      {
        id: "h11",
        name: "虾仁炒蛋",
        description: "滑嫩可口，营养丰富",
        price: 12,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish2.png",
        count: 0,
      },
      {
        id: "h12",
        name: "鱼香肉丝",
        description: "开胃下饭，香味四溢",
        price: 10,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish3.png",
        count: 0,
      },
    ],
    personalDishes: [],
    cartCount: 0,
    cartTotal: 0,
    deliveryTime: "12:30",
    dishes: [],
    searchValue: "",
    isLogin: false,
    showRecommendTip: false,
    acceptRecommend: false,
    filteredDishes: [],
    showEmpty: false,
    defaultImage: '/images/dishes/default-dish.png'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadCartInfo();
    this.checkLoginStatus();
    this.loadDishes();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkLoginStatus();
    this.loadCartInfo();
    // 检查是否已有个性化推荐授权
    const hasConsent = wx.getStorageSync("personalRecommendConsent");
    this.setData({ hasUserConsent: hasConsent });
    if (hasConsent) {
      this.loadPersonalRecommendations();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},

  switchCategory(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({ currentCategory: category });
  },

  handleUserConsent(e) {
    const consent = e.currentTarget.dataset.consent;
    if (consent) {
      wx.setStorageSync("personalRecommendConsent", true);
      this.setData({ hasUserConsent: true });
      this.loadPersonalRecommendations();
    } else {
      this.setData({ currentCategory: "hot" });
    }
  },

  loadPersonalRecommendations() {
    // TODO: 调用后端API获取个性化推荐
    // 这里使用模拟数据
    const personalDishes = [
      {
        id: "p1",
        name: "私人推荐1",
        description: "根据您的口味定制",
        price: 45,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish1.png",
        count: 0,
      },
      {
        id: "p2",
        name: "私人推荐2",
        description: "专属美味",
        price: 38,
        image: "cloud://cloudbase-9gfwuqmufc240632.636c-cloudbase-9gfwuqmufc240632-1349875107/dishes/dish2.png",
        count: 0,
      },
    ];
    this.setData({
      personalDishes,
    });
  },

  onSearch(e) {
    const searchValue = e.detail.value.toLowerCase();
    const filteredDishes = this.data.dishes.filter(
      (dish) => dish.name.toLowerCase().indexOf(searchValue) !== -1
    );

    this.setData({
      searchValue,
      filteredDishes,
      showEmpty: searchValue && filteredDishes.length === 0,
    });
  },

  addToCart(e) {
    if (!this.data.isLogin) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }

    const { id } = e.currentTarget.dataset;
    let dish = null;

    // 查找菜品
    for (let item of this.data.hotDishes) {
      if (item.id === id) {
        dish = item;
        break;
      }
    }

    if (!dish) {
      for (let item of this.data.personalDishes) {
        if (item.id === id) {
          dish = item;
          break;
        }
      }
    }

    if (!dish) {
      wx.showToast({
        title: '菜品不存在',
        icon: 'none'
      });
      return;
    }

    // 获取购物车
    let cartItems = wx.getStorageSync('cartItems') || [];
    let found = false;

    // 查找是否已在购物车中
    for (let item of cartItems) {
      if (item.id === id) {
        item.quantity++;
        found = true;
        break;
      }
    }

    // 如果不在购物车中，添加新项
    if (!found) {
      cartItems.push({
        id: dish.id,
        name: dish.name,
        price: dish.price,
        image: dish.image,
        quantity: 1
      });
    }

    // 保存购物车
    wx.setStorageSync('cartItems', cartItems);

    // 更新购物车数量和总价
    this.loadCartInfo();

    wx.showToast({
      title: '已添加到购物车',
      icon: 'success'
    });
  },

  minusFromCart(e) {
    const id = e.currentTarget.dataset.id;
    const dishes =
      this.data.currentCategory === "hot"
        ? this.data.hotDishes
        : this.data.personalDishes;
    const dish = dishes.find((d) => d.id === id);

    if (dish && dish.count > 0) {
      dish.count -= 1;
      this.updateDishList(dishes);
      this.updateCartState();
      this.saveCartInfo();
    }
  },

  updateDishList(dishes) {
    if (this.data.currentCategory === "hot") {
      this.setData({ hotDishes: dishes });
    } else {
      this.setData({ personalDishes: dishes });
    }
  },

  saveCartInfo() {
    const cartInfo = {
      hotDishes: this.data.hotDishes,
      personalDishes: this.data.personalDishes,
    };
    wx.setStorageSync("cartInfo", cartInfo);
  },

  loadCartInfo() {
    const cartItems = wx.getStorageSync('cartItems') || [];
    let cartCount = 0;
    let cartTotal = 0;

    cartItems.forEach(item => {
      cartCount += item.quantity;
      cartTotal += item.price * item.quantity;
    });

    this.setData({
      cartCount,
      cartTotal: cartTotal.toFixed(2)
    });
  },

  updateCartState() {
    let count = 0;
    let total = 0;

    const calculateDishes = (dishes) => {
      dishes.forEach((dish) => {
        if (dish.count > 0) {
          count += dish.count;
          total += dish.price * dish.count;
        }
      });
    };

    calculateDishes(this.data.hotDishes);
    calculateDishes(this.data.personalDishes);

    this.setData({
      cartCount: count,
      cartTotal: total.toFixed(2),
    });
  },

  showDishDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/dish/detail?id=${id}`,
    });
  },

  checkout() {
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.showModal({
        title: "提示",
        content: "请先登录后再结算",
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/login/login",
            });
          }
        },
      });
      return;
    }

    wx.navigateTo({
      url: "/pages/order/checkout",
    });
  },

  checkLoginStatus() {
    const isLogin = auth.checkLoginStatus();
    this.setData({
      isLogin,
      showRecommendTip: !!isLogin && !wx.getStorageSync("acceptRecommend"),
    });
    return isLogin;
  },

  loadDishes: async function() {
    try {
      const db = wx.cloud.database();
      const dishes = await db.collection('dishes').get();
      
      // 处理每个菜品的图片URL
      const processedDishes = await Promise.all(dishes.data.map(async dish => {
        if (dish.image && dish.image.includes('cloud://')) {
          try {
            const { fileList } = await wx.cloud.getTempFileURL({
              fileList: [dish.image]
            });
            return {
              ...dish,
              image: fileList[0].tempFileURL || this.data.defaultImage
            };
          } catch (err) {
            console.error('获取图片临时链接失败：', err);
            return {
              ...dish,
              image: this.data.defaultImage
            };
          }
        }
        return dish;
      }));

      this.setData({
        dishes: processedDishes
      });
    } catch (err) {
      console.error('加载菜品失败：', err);
      wx.showToast({
        title: '加载菜品失败',
        icon: 'none'
      });
    }
  },

  acceptRecommend() {
    wx.setStorageSync("acceptRecommend", true);
    this.setData({
      showRecommendTip: false,
      acceptRecommend: true,
    });
    // TODO: 调用推荐系统API
  },

  rejectRecommend() {
    wx.setStorageSync("acceptRecommend", false);
    this.setData({
      showRecommendTip: false,
      acceptRecommend: false,
    });
  },

  goToLogin() {
    wx.navigateTo({
      url: "/pages/login/login",
    });
  },

  // 图片加载失败处理
  handleImageError: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      [`dishes[${index}].image`]: this.data.defaultImage
    });
  }
});
